package com.bawei.login.vm

import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.login.intent.LoginViewIntent
import com.bawei.login.model.LoginRepositoryHilt
import com.bawei.login.state.LoginUiState
import com.blankj.utilcode.util.GsonUtils
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.parse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2024/8/23
 * Desc:
 */
@HiltViewModel
class LoginViewModel @Inject constructor(private val repository: LoginRepositoryHilt): BaseViewModel<LoginViewIntent>(){

    private val _uiSate = MutableStateFlow<LoginUiState>(LoginUiState.NoneState) //当前类中使用，可以修改流中数据
    val uiState: StateFlow<LoginUiState> = _uiSate.asStateFlow() //只用于外部接收流中的数据

    override fun dispatchIntent(intent: LoginViewIntent) {
        when(intent){
            is LoginViewIntent.LoginToServer -> loginToServer(intent.name, intent.pwd)
            is LoginViewIntent.RegisterToServer -> registerToServer(intent.name, intent.pwd)
            else -> {}
        }
    }


    private fun loginToServer(name: String, pwd: String){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //封装参数
                var mapParams = mutableMapOf("uName" to name, "uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis() / 1000).toString()
                var jsonParams = GsonUtils.toJson(mapParams)
                var paramsBody = jsonParams.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

                //调用仓库中挂起方法
                var resultData = repository.loginToServer(paramsBody)
                if (resultData.statuesCode == "200"){
                    MMKV.defaultMMKV().encode("token", resultData.getValues().token)
                    MMKV.defaultMMKV().encode("home_url", resultData.home)
                    MMKV.defaultMMKV().encode("userId", resultData.getValues().uId)
                    _uiSate.value = LoginUiState.LoginSuccess(resultData.getValues())
                } else {
                    _uiSate.value = LoginUiState.LoginFail(resultData.msg)
                }
            } catch (e: Exception){
                e.printStackTrace()
                _uiSate.value = LoginUiState.LoginFail(e.message ?: "接口异常，请联系客服！" )
            } finally {
                //取消协程
                cancel()
            }
        }
    }

    private fun registerToServer(name: String, pwd: String){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //封装参数
                var mapParams = mutableMapOf<String, Any>("pId" to 0, "uName" to name, "uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis() / 1000).toString() //时间戳
                var jsonParams = GsonUtils.toJson(mapParams)
                var paramsBody = jsonParams.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

                //调用仓库中挂起方法
                var resultData = repository.registerToServer(paramsBody)
                if (resultData.statuesCode == "200"){
                    _uiSate.value = LoginUiState.RegisterSuccess(resultData.getValues())
                } else {
                    _uiSate.value = LoginUiState.RegisterFail(resultData.msg)
                }
            } catch (e: Exception){
                e.printStackTrace()
                _uiSate.value = LoginUiState.RegisterFail(e.message ?: "接口异常，请联系客服！" )
            } finally {
                //取消协程
                cancel()
            }
        }
    }



}